package com.eliauk.demo.controller.write;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.ListUtils;
import com.eliauk.demo.entity.wirte.ImageDemoData;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("write7")
public class write7Controller {

    /**
     * 图片的导出 一般都会直接使用URL去接收数据库的记录图片的url,或者使用二进制字节数组
     * @return
     */
    @GetMapping("download")
    public String exportData(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        List<ImageDemoData> list = getImageData();

        EasyExcel.write(out, ImageDemoData.class).sheet().doWrite(list);
        return "success";
    }


    public List<ImageDemoData> getImageData() throws IOException {
        List<ImageDemoData> list =  ListUtils.newArrayList();
        ImageDemoData imageDemoData = new ImageDemoData();
        list.add(imageDemoData);
        // 放入五种类型的图片 实际使用只要选一种即可
        String imagePath ="D:\\excel\\upload\\excelUpload\\TestEntity\\test.png";
        File file = new File(imagePath);
        InputStream inputStream = new FileInputStream(file);

        //五张图片
        imageDemoData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath)));
        imageDemoData.setFile(new File(imagePath));
        imageDemoData.setString(imagePath);
        imageDemoData.setInputStream(inputStream);
        imageDemoData.setUrl(new URL("http://hbimg.huaban.com/1445ceb6299728867ce9d09e173fe1c976f6ee0c395c2b-3HW21D"));
        return list;
    }


}
